package com.vivo.dingtalk.web;

import com.dingtalk.api.response.OapiWorkrecordAddResponse;
import com.dingtalk.api.response.OapiWorkrecordUpdateResponse;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.vivo.Utils.SendDingDingMsgUtil;
import com.vivo.dingtalk.entity.DingUserInfo;
import com.vivo.dingtalk.entity.DingWorkRecord;
import com.vivo.dingtalk.service.DingUserInfoService;
import com.vivo.dingtalk.service.DingWorkRecordService;
import com.vivo.dingtalk.web.vm.ResultVM;
import com.vivo.dingtalk.web.vm.WorkRecordVM;
import com.vivo.employee.service.ViEmployeeService;
import com.vivo.system.entity.VivoDingConf;
import com.vivo.system.service.VivoDingConfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/ding")
public class DingApiController extends BaseController {
    @Autowired
    private DingWorkRecordService dingWorkRecordService;

    @Autowired
    private ViEmployeeService viEmployeeService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private DingUserInfoService dingUserInfoService;

    @Autowired
    private VivoDingConfService vivoDingConfService;

    /**
     * 添加钉钉备忘信息
     * @param workRecordVM
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addWR", method = RequestMethod.POST)
    public ResultVM addWR(@RequestBody WorkRecordVM workRecordVM) {
        ResultVM resultVM = null;
        System.out.println(workRecordVM);

        do {
            if (workRecordVM.getEmpId() == null && workRecordVM.getPhone() == null) {
                resultVM = ResultVM.error(-1, "参数不全，员工编号与手机号码不能都为空！");
                continue;
            }

            if (StringUtils.isBlank(workRecordVM.getTitle()) || StringUtils.isBlank(workRecordVM.getUrl()) ||
                    StringUtils.isBlank(workRecordVM.getFormTitle()) || StringUtils.isBlank(workRecordVM.getFormCont())){
                resultVM = ResultVM.error(-1, "参数不全，缺少title,url,formTitle,formCont等参数！");
                continue;
            }

            User user = null;
            if (!StringUtils.isBlank(workRecordVM.getEmpId())) {
                user = systemService.getUserByEmpId(workRecordVM.getEmpId());
            } else if (!StringUtils.isBlank(workRecordVM.getPhone())) {
                user = systemService.getUserByLoginName(workRecordVM.getPhone());
            }

            if (user == null) {
                resultVM = ResultVM.error(-2, "找不到对应的用户信息！");
                continue;
            }

            DingUserInfo dingUserInfo = dingUserInfoService.getByMobile(user.getLoginName());
            if (dingUserInfo == null) {
                resultVM = ResultVM.error(-3, "找不到对应的用户钉钉登陆信息！请提醒其进行钉钉登陆操作！");
                continue;
            }

            VivoDingConf dingConf = vivoDingConfService.getByComp(user.getCompany().getId());
            if (dingConf == null) {
                resultVM = ResultVM.error(-4, "该二级区域还没有进行钉钉绑定设置，提醒管理员进行相关绑定操作！二级区域："
                        + user.getCompany().getName());
                continue;
            }

            workRecordVM.setAccessToken(dingConf.getAccessToken());
            workRecordVM.setDingUserId(dingUserInfo.getDingUserId());

            OapiWorkrecordAddResponse rsp = null;
            try {
                rsp = SendDingDingMsgUtil.sendWorkRecord(workRecordVM);

                if (rsp.getErrcode() != 0L) {
                    resultVM = ResultVM.error(-6, rsp.getErrmsg());
                    continue;
                }
            } catch (Exception e) {
                resultVM = ResultVM.error(-5, "操作失败！" + e.getMessage());
                continue;
            }

            DingWorkRecord dingWorkRecord = new DingWorkRecord();
            dingWorkRecord.setComp(user.getCompany());
            dingWorkRecord.setDingUserId(dingUserInfo.getDingUserId());
            dingWorkRecord.setEmpId(user.getEmployeeId());
            dingWorkRecord.setUser(user);
            dingWorkRecord.setFormTitle1(workRecordVM.getFormTitle());
            dingWorkRecord.setFormCont1(workRecordVM.getFormCont());
            dingWorkRecord.setTitle(workRecordVM.getTitle());
            dingWorkRecord.setUrl(workRecordVM.getUrl());
            dingWorkRecord.setRecordId(rsp.getRecordId());
            dingWorkRecord.setStatus("待办中");
            try {
                dingWorkRecordService.save(dingWorkRecord);
            } catch (Exception e) {
                try {
                    // 如果存取失败，必须清除待办信息
                    SendDingDingMsgUtil.updWorkRecord(workRecordVM.getAccessToken(), workRecordVM.getDingUserId(), rsp.getRecordId());
                } catch (Exception ex) {
                    resultVM = ResultVM.error(-7, ex.getMessage());
                    continue;
                }
            }

            resultVM = ResultVM.ok("钉钉代办添加成功！");
            if (rsp != null) {
                resultVM.setResult(rsp.getRecordId());
            }
        } while (false);

        return resultVM;
    }

    @ResponseBody
    @RequestMapping(value = "/cancelWR", method = RequestMethod.POST)
    public ResultVM cancelWR(@RequestBody WorkRecordVM workRecordVM) {
        if (workRecordVM.getRecordId() == null || StringUtils.isBlank(workRecordVM.getRecordId())) {
            return ResultVM.error(-1, "参数不全，待办编号不能为空！");
        }

        DingWorkRecord dingWorkRecord = dingWorkRecordService.getByRecordId(workRecordVM.getRecordId());
        if (dingWorkRecord == null) {
            return ResultVM.error(-2, "找不到对应的待办信息！");
        }

        VivoDingConf dingConf = vivoDingConfService.getByComp(dingWorkRecord.getComp().getId());
        if (dingConf == null) {
            return ResultVM.error(-3, "找不到对应二级的配置信息！" + dingWorkRecord.getComp().getName());
        }

        try {
            OapiWorkrecordUpdateResponse rsp = SendDingDingMsgUtil.updWorkRecord(dingConf.getAccessToken(), dingWorkRecord.getDingUserId(), dingWorkRecord.getRecordId());
            if (rsp.getErrcode() == 0) {
                dingWorkRecord.setStatus("完成待办");
            } else {
                dingWorkRecord.setRemarks(rsp.getErrmsg());
            }
            dingWorkRecordService.save(dingWorkRecord);
        } catch (Exception e) {
            return ResultVM.error(-4, e.getMessage());
        }

        return ResultVM.ok();
    }
}
